package com.ytjj.qmyx.admin.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.gexin.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.qmyx.admin.config.CommonPropertiesConfig;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.qmyx.admin.dao.*;
import com.ytjj.qmyx.admin.eunm.ActivityEnums;
import com.ytjj.qmyx.admin.eunm.ProductActivityTypeEnums;
import com.ytjj.qmyx.admin.mapper.AdminMapper;
import com.ytjj.qmyx.admin.mapper.ProductSkuKeyMapper;
import com.ytjj.qmyx.admin.mapper.ProductSkuValueMapper;
import com.ytjj.qmyx.admin.model.ProductSkuKey;
import com.ytjj.qmyx.admin.model.ProductSkuValue;
import com.ytjj.qmyx.admin.model.request.BankerProductRequest;
import com.ytjj.qmyx.admin.model.request.ProductVerifyRequest;
import com.ytjj.qmyx.admin.model.request.bankerProduct.BankerProductImgRequest;
import com.ytjj.qmyx.admin.model.request.bankerProduct.BankerProductSkuKeyRequest;
import com.ytjj.qmyx.admin.model.request.bankerProduct.BankerProductSpecRequest;
import com.ytjj.qmyx.admin.model.response.BankerProduct.BankerProductDetailResponse;
import com.ytjj.qmyx.admin.model.response.BankerProductResponse;
import com.ytjj.qmyx.admin.service.BankerProductService;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 
 * @Version: 1.0
 */
@Service
@Slf4j
public class BankerProductServiceImpl implements BankerProductService {

    @Autowired
    private BankerProductDao bankerProductDao;

    @Autowired
    private BankerMessageDao bankerMessageDao;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private BankerProductImgMapper bankerProductImgMapper;

    @Resource
    private BankerProductSpecMapper bankerProductSpecMapper;

    @Resource
    private BankerProductSkuKeyMapper bankerProductSkuKeyMapper;

    @Resource
    private BankerProductSkuValueMapper bankerProductSkuValueMapper;

    @Resource
    private ProductImgMapper productImgMapper;

    @Resource
    private ProductSpecMapper productSpecMapper;

    @Resource
    private ProductSpecDao productSpecDao;

    @Resource
    private ProductSkuKeyMapper productSkuKeyMapper;

    @Resource
    private ProductSkuValueMapper productSkuValueMapper;

    @Resource
    private BankerDao bankerDao;

    @Resource
    private ProductDao productDao;

    @Resource
    private ProductCategoryMapper productCategoryMapper;

    @Resource
    private ProductSpecialMapper productSpecialMapper;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private CommonPropertiesConfig commonPropertiesConfig;

    @Resource
    private SupplyApiConfig supplyApiConfig;

    @Override
    public CommonPage<BankerProductResponse> selectList(BankerProductRequest bankerProductRequest) {
        PageHelper.startPage(bankerProductRequest.getPageNum(), bankerProductRequest.getPageSize());
//        String curUserEmail = UserUtil.getPrincipal();
//        int adminId =adminMapper.adminId(curUserEmail);
//        bankerProductRequest.setAdminId(adminId);
        List<BankerProductResponse> pageList = bankerProductDao.selectList(bankerProductRequest);
        if(!CollectionUtils.isEmpty(pageList)) {
            for(BankerProductResponse bp : pageList) {
                // 供应商商品->商品管理 所属活动
                List<String> activityList = productDao.getActivityType(bp.getId());
                if (!CollectionUtils.isEmpty(activityList)) {
                    String activityType = activityList.get(0);
                    bp.setActivityType(ProductActivityTypeEnums.getName(activityType));
                }

                if(bp.getTopCategoryId() != null) {
                    ProductCategory pc = productCategoryMapper.selectByPrimaryKey(bp.getTopCategoryId());
                    if(null != pc)
                        bp.setOneTitle(pc.getTitle());
                }
                if(bp.getCategoryId() != null) {
                    ProductCategory pc = productCategoryMapper.selectByPrimaryKey(bp.getCategoryId());
                    if(null != pc)
                        bp.setTwoTitle(pc.getTitle());
                }
                if(bp.getBottomCategoryId() != null) {
                    ProductCategory pc = productCategoryMapper.selectByPrimaryKey(bp.getBottomCategoryId());
                    if(null != pc)
                        bp.setThreeTitle(pc.getTitle());
                }
            }
        }
        return CommonPage.restPage(pageList);
    }

    @Override
    public String newSelectList(BankerProductRequest bankerProductRequest) {
        String json = JSON.toJSONString(bankerProductRequest);
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/banker/productList", json, supplyApiConfig.getHeadsMap());
        return resultJson;
    }

    @Override
    public Integer verifyFail(ProductVerifyRequest productVerifyRequest) {
        Integer count = bankerProductDao.verifyFail(productVerifyRequest.getId(), productVerifyRequest.getVerifyRemarks());
        if (count > 0) {
            BankerMessage message = new BankerMessage();
            message.setBankerId(productVerifyRequest.getBankerId());
            message.setBankerProductId(productVerifyRequest.getId());
            message.setProductName(productVerifyRequest.getProductName());
            message.setRemarks("您的商品："+productVerifyRequest.getProductName()+" 未能成功通过审核！(原因："+productVerifyRequest.getVerifyRemarks()+")");
            message.setStatus(0);
            message.setType(2);
            message.setCreateTime(new Date());
            bankerMessageDao.insertMessage(message);
        }
        return count;
    }

    @Override
    public String newVerifyFail(ProductVerifyRequest productVerifyRequest) {
        String json = JSON.toJSONString(productVerifyRequest);
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/banker/verifyFailProduct", json, supplyApiConfig.getHeadsMap());
        return resultJson;
    }

    @Override
    public Integer udpateStatus(Integer id) {
        BankerProductResponse bankerProduct = bankerProductDao.getBankerProduct(id);
        Integer count = 0;
        // 上下架状态 1-上架 2-下架
        if(bankerProduct.getStatus() == 1) {
            count = bankerProductDao.updateStatus(bankerProduct.getId(), 2);
        } else {
            count = bankerProductDao.updateStatus(bankerProduct.getId(), 1);
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer syncBankerToProduct(Product product) {

        Integer isExists = productDao.isExists(product.getId());
        if(isExists > 0) {
            throw new ApiException("该供应商商品已审核通过，暂不支持重复审核！");
        }
        //商品分类同步到供应商商品
        productDao.updateCategoryId(product.getId(),product.getTopCategoryId(),product.getCategoryId(),product.getBottomCategoryId(),product.getAppraisalType());
        // 1.供应商产品-->普通产品库
        // 商品审核通过 状态为：待上架
        product.setBankerProductId(product.getId());
        product.setAuditStatus(1);
        // 审核时不是0元测评商品时，isZeroProduct改为0-否
        if(product.getBankerColumnId() != 3) {
            product.setIsZeroProduct(0);
        } else {
            product.setIsZeroProduct(1);
            product.setProductType(2);
            if (StringUtils.isEmpty(product.getActivityType())) {
                product.setActivityType(ActivityEnums.ZERO_EVALUATION.getActivityCode());
            }
        }
        Product insertProduct = new Product();
        List<Product> existList = productDao.selectByBankerProductId(product.getId());

        BeanUtils.copyProperties(product, insertProduct);
        if (!CollectionUtils.isEmpty(existList)) {
            insertProduct.setId(existList.get(0).getId());
        }else {
            insertProduct.setId(null);
        }
        // 审核通过 把商品名称赋值给长标题
        insertProduct.setLongTitle(product.getProductName());
        insertProduct.setBrandId(null);
        insertProduct.setStatus((byte) 4);
        Integer insertCount = 0;
        Integer updateCount = 0;
        if (null == insertProduct.getId()) {
            insertProduct.setCreateTime(new Date());
            //费率
            insertProduct.setRate(BigDecimal.valueOf(1));
            if (StringUtils.isEmpty(insertProduct.getRecDescr())){
                //推荐描述
                insertProduct.setRecDescr(insertProduct.getDescr());
            }
            if (StringUtils.isEmpty(insertProduct.getRecommendDoc())){
                //推荐文案
                insertProduct.setRecommendDoc(insertProduct.getDescr());
            }
            insertProduct.setRecDescr(null);
            insertProduct.setAppraisalType(null == product.getAppraisalType() ? 1 : product.getAppraisalType());
            insertCount = productMapper.insertSelective(insertProduct);
        }else {
            insertProduct.setRecDescr(null);
            insertProduct.setUpdateTime(new Date());
            updateCount = productMapper.updateByPrimaryKeySelective(insertProduct);
        }

        //主键自增拿到增加后的productId
        Integer productId = insertProduct.getId();

        // 2.同步商品img
        if (updateCount > 0){
            productImgMapper.deleteByProductId(productId);
        }
        BankerProductImgExample bankerProductImgExample = new BankerProductImgExample();
        bankerProductImgExample.createCriteria().andProductIdEqualTo(product.getId());
        List<BankerProductImg> bpImgList = bankerProductImgMapper.selectByExample(bankerProductImgExample);
        if(!CollectionUtils.isEmpty(bpImgList)) {
            for(BankerProductImg bpi : bpImgList) {
                ProductImg pi = new ProductImg();
                pi.setProductId(productId);
                pi.setImgUrl(bpi.getImgUrl());
                pi.setSort(bpi.getSort());
                pi.setFileType(bpi.getFileType());
                pi.setType(bpi.getType());
                pi.setCreateTime(new Date());
                productImgMapper.insertSelective(pi);
            }
        }

        // 3.同步商品spec
        if (updateCount > 0){
            productSpecDao.deleteByProductId(productId);
        }
        BankerProductSpecExample bankerProductSpecExample = new BankerProductSpecExample();
        bankerProductSpecExample.createCriteria().andProductIdEqualTo(product.getId());
        List<BankerProductSpec> bpSpecList = bankerProductSpecMapper.selectByExample(bankerProductSpecExample);
        if(!CollectionUtils.isEmpty(bpImgList)) {
            for(BankerProductSpec bps : bpSpecList) {
                ProductSpec ps = new ProductSpec();
                ps.setProductId(productId);
                ps.setSkuSpec(bps.getSkuSpec());
                // 售价
                ps.setPrice(product.getPrice());
                // 直接购买价
                ps.setCurPrice(product.getCurPrice());
                // 原价
                ps.setOriginalPrice(bps.getOriginalPrice());
                // 同步供应商商品-规格-成本价格
                ps.setCostPrice(bps.getPrice());
                ps.setProImg(bps.getProImg());
                ps.setBuySum(product.getVolume());
                ps.setStock(bps.getStock());
                ps.setStatus(bps.getStatus());
                ps.setBankerProductId(bps.getProductId());
                ps.setCreateTime(new Date());
                ps.setThreeSkuId(bps.getThreeSkuId());
                productSpecMapper.insertSelective(ps);
            }
        }

        // 4.同步商品sku_key
        if (updateCount > 0){
            productSkuKeyMapper.deleteByProductId(productId);
            productSkuValueMapper.deleteByProductId(productId);
        }
        BankerProductSkuKeyExample bankerProductSkuKeyExample = new BankerProductSkuKeyExample();
        bankerProductSkuKeyExample.createCriteria().andPidEqualTo(product.getId());
        List<BankerProductSkuKey> bpskList = bankerProductSkuKeyMapper.selectByExample(bankerProductSkuKeyExample);
        if(!CollectionUtils.isEmpty(bpskList)) {
            for(BankerProductSkuKey bpsk : bpskList) {
                ProductSkuKey psk = new ProductSkuKey();
                psk.setPid(productId);
                psk.setKid(bpsk.getKid());
                psk.setName(bpsk.getName());
                psk.setSort(bpsk.getSort());
                psk.setCreateTime(new Date());
                productSkuKeyMapper.insertSelective(psk);
                // 5.同步商品sku_value
                BankerProductSkuValueExample bankerProductSkuValueExample = new BankerProductSkuValueExample();
                bankerProductSkuValueExample.createCriteria().andPidEqualTo(product.getId()).andKidEqualTo(bpsk.getId()).andStatusEqualTo((byte) 1);
                List<BankerProductSkuValue> bpsvList = bankerProductSkuValueMapper.selectByExample(bankerProductSkuValueExample);
                if(!CollectionUtils.isEmpty(bpsvList)) {
                    for(BankerProductSkuValue bpsv : bpsvList) {
                        ProductSkuValue psv = new ProductSkuValue();
                        psv.setPid(productId);
                        psv.setVid(bpsv.getVid());
                        psv.setKid(psk.getId());
                        psv.setValue(bpsv.getValue());
                        psv.setSort(bpsv.getSort());
                        psv.setStatus(bpsv.getStatus());
                        psv.setCreateTime(new Date());
                        productSkuValueMapper.insertSelective(psv);
                    }
                }
            }
        }

        // 6.消息通知 供应商商品-->普通商品库
        BankerMessage message = new BankerMessage();
        message.setBankerId(product.getBankerId());
        message.setBankerProductId(product.getId());
        message.setProductName(product.getProductName());
        message.setRemarks("您的商品："+product.getProductName()+" 已成功通过审核！");
        message.setStatus(0);
        message.setType(1);
        message.setCreateTime(new Date());
        bankerMessageDao.insertMessage(message);

//        // 7.商品审核通过，供应商商品状态修改为审核通过状态 官网栏目也做同步
//        bankerProductDao.updateAuditStatus(product.getId(), 1,product.getAppraisalType());
//        bankerProductDao.synvBankerColumn(product.getId(), product.getBankerColumnId());

//        // 8.供应商商品总数 +1
//        bankerDao.addProductNum(product.getBankerId());

//        // 9.同步供应商 0元适用商品数量
//        Integer zeroNum = productDao.getZeroCount(product.getBankerId());
//        bankerDao.syncZeroNum(product.getBankerId(), zeroNum);

        // 10.审核选择所属专区后，默认添加该商品至专区商品列表中
        ProductSpecial productSpecial = new ProductSpecial();
        productSpecial.setSpecialId(product.getSpecialId());
        productSpecial.setProductId(productId);
        productSpecial.setType("COMMON");
        productSpecial.setRecommendFlag(0);
        productSpecial.setSort(1);
        productSpecial.setStatus((byte) 2);
        productSpecial.setCreateTime(new Date());
        productSpecial.setUpdateTime(new Date());
        productSpecialMapper.insertSelective(productSpecial);

        return insertCount > 0 ? insertCount: updateCount;
    }

    @Override
    public String newSyncBankerToProduct(Product Product) {
        String json = JSON.toJSONString(Product);
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/syncBankerToProduct", json, supplyApiConfig.getHeadsMap());
        return resultJson;
    }

    @Override
    public BankerProductDetailResponse bankerProductDetail(Integer productId) {
//        BankerProductDetailResponse detailInfo = bankerProductDao.findInfoById(productId);
        BankerProductDetailResponse detailInfo = new BankerProductDetailResponse();
        List<BankerProductDetailResponse> bankerProductDetailResponseList = bankerProductDao.findInfoById(productId);

        if (!CollectionUtils.isEmpty(bankerProductDetailResponseList)) {
            if (bankerProductDetailResponseList.size() == 1) {
                detailInfo = bankerProductDetailResponseList.get(0);
            }else {
                bankerProductDetailResponseList.stream().sorted((stu1, stu2) ->
                        Long.compare(stu2.getProductCreatTime().getTime(), stu1.getProductCreatTime().getTime()))
                        .forEach(System.out::println);
                detailInfo = bankerProductDetailResponseList.get(0);
            }
        }

        List<BankerProductSkuKeyRequest> skuKey = bankerProductDao.findSku(productId);
        List<BankerProductImgRequest> bannerList = bankerProductDao.findImg(productId,"banner");
        List<BankerProductImgRequest> infoList = bankerProductDao.findImg(productId,"info");
        List<BankerProductSpecRequest> spec  = bankerProductDao.findSpec(productId);
        detailInfo.setSkuKey(skuKey);
        detailInfo.setBannerList(bannerList);
        detailInfo.setInfoList(infoList);
        detailInfo.setSpec(spec);
        return detailInfo;
    }

    @Override
    public String newBankerProductDetail(Integer productId) {
        Map map = new HashMap();
        map.put("productId",String.valueOf(productId));
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/bankerProductDetail", map, supplyApiConfig.getHeadsMap());
        return resultJson;
    }

    @Override
    public String newProductDetail(Integer productId) {
        Map map = new HashMap();
        map.put("productId",String.valueOf(productId));
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/productDetail", map, supplyApiConfig.getHeadsMap());
        return resultJson;
    }

}
